﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;



namespace 连接
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //增添数据
        private void button1_Click(object sender, EventArgs e)
        {
            //跳转删除窗体
            Form4 form4 = new Form4();
            form4.ShowDialog();
        }

        //查询数据
        private void button2_Click(object sender, EventArgs e)
        {
            //编写数据库连接串
            string connStr = "Data Source=.;Initial Catalog=sa;User ID=sa;Password=po89090";
            //创建 SqlConnection的实例
            SqlConnection conn = null;
            //定义SqlDataReader类的对象
            SqlDataReader dr = null;
            try
            {
                conn = new SqlConnection(connStr);
                //打开数据库连接
                conn.Open();
                string sql = "select name,idcode from student where idcode='{0}'";
                //填充SQL语句
                sql = string.Format(sql, textBox2.Text);
                //输入不能为空
                if (textBox2.Text == "")
                {
                    //用户名为空
                    MessageBox.Show("学号不能为空！");
                    return;
                }
                //创建SqlCommand对象
                SqlCommand cmd = new SqlCommand(sql, conn);
                //执行Sql语句
                dr = cmd.ExecuteReader();
                //判断SQL语句是否执行成功
                if (dr.Read())
                {
                    //读取指定用户名对应的用户编号和密码
                    string msg = "姓名：" + dr[0] + " 学号：" + dr[1];
                    //将msg的值显示在标签上
                    label2.Text = msg;
                }
                else
                {
                    //读取指定用户名对应的用户编号和密码
                    string msg = "无此人信息";
                    //将msg的值显示在标签上
                    label2.Text = msg;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("查询失败！" + ex.Message);
            }
            finally
            {
                if (dr != null)
                {
                    //判断dr不为空，关闭SqlDataReader对象
                    dr.Close();
                }
                if (conn != null)
                {
                    //关闭数据库连接
                    conn.Close();
                }
            }
        }

        //修改数据
        private void button3_Click(object sender, EventArgs e)
        {
            //跳转修改窗体
            Form2 form2 = new Form2();
            form2.ShowDialog();
        }

        //删除数据
        private void button4_Click(object sender, EventArgs e)
        {
            //跳转删除窗体
            Form3 form3 = new Form3();
            form3.ShowDialog();
        }

        
    }
}
